import { reactive } from 'vue'
import { defineStore } from 'pinia'
import {
	deleteNotifications,
	getBonusActivities,
	getBonusStat,
	getNotifications,
	getProgressive,
	getRewardsConfig,
	getStarList,
	getUpgradeRule,
	getVipList,
	receiveBonus
	// resUserUpgradeInfo
} from '@/api/activity.ts'
import {
	useAccountStore,
	useAppStore,
	useProfileStore,
	useWalletStore,
	useMemberStore
} from '@/store'
import { Decimals } from '@/utils/decimal.ts'
import { Member } from '@/types'
import {
	ActivityBonusKeys,
	ActivityCashbackKeys,
	ActivityRewardType,
	CasinoRebateKeys,
	SlotsRebateKeys,
	SportsRebateKeys
} from '@/enums/activity-reward-type.ts'
import { BettingStatus, RewardsEnumDiff, RewardsHome, RewardStatusEnum } from '@/enums'
import { goDetails, percentage, t } from '@/utils'
import { find, keyBy, merge } from 'lodash-es'
import { getBetList } from '@/api/betting.ts'
import { getSlotsRecordDetailList } from '@/api/slots.ts'
import { BetType } from '@/enums'
import router from '@/router'
// import { RewardsHome } from '@/enums'

const initState = () => {
	return {
		activities: null as any,
		activitiesObj: {} as any,
		config: null,
		upgradeRule: {
			vip: {
				casino: { left: 0, right: 0 },
				slot: { left: 0, right: 0 },
				sport: { left: 0, right: 0 }
			},
			star: {
				sport: { left: 0, right: 0 }
			}
		},
		notifications: {
			// 这里的顺序 决定弹窗的优先级
			successFtd: null,
			upgradeVip: null,
			upgradeStar: null,
			obtainChance: null,
			successReload: null
		} as any,
		// rewardsStatus 各种奖金状态的数据结构,可用于首页和奖金记录页
		// 所有金额数值都区分不同货币
		status: {
			deposit: initState.deposit(),
			lockBonus: initState.lockBonus(),
			reloadDeposit: initState.reloadDeposit(),
			// 周奖金
			weeklyReward: {
				endTimestamp: 0,
				// 1.等待中; 2.计算中; 3.可领取
				status: '',
				value: 0
			},
			// 已领取 的各种奖金
			receivedBonus: {
				origin: {
					firstCharge: 0
					// 首充奖金  firstCharge / firstTimeDepositBonus
					// VIP升级奖金  upgradeBonus
					// 再充奖金  reloadBonus
					// RFC奖金  RFC
					// 大师杯奖金  CupBonus
					// 周奖金  **
				},
				value: 0
			},
			// 可领取的 各种救援金
			cashback: {
				origin: {
					// 体育救援金  sportsCashback
					// 赌场救援金  casinoCashback
					// 电子救援金  slotsCashback
				},
				value: 0
			},
			// 可领取的 体育相关的返利
			sportsRebate: {
				origin: {
					// 体育返利  sportsRebate
					// STAR 被跟赢注返利  referralWinBonus
					// STAR 被跟输注返利  referralLoseBonus
					// VIP跟输注返利  copiedLoseBonus
				},
				value: 0
			},
			// 可领取的 电子返利
			slotsRebate: {
				value: 0
			},
			// 可领取的 赌场返利
			casinoRebate: {
				value: 0
			},
			// 过期奖金
			expireBonus: {
				value: 0
			}
		} as any,
		// 解锁奖金的注单明细,投注记录
		unlockBetRecord: {
			// [betType]:{ [orderNo]:{} }
		} as any
	}
}

// 首充,(旧首充/新首充 取最高奖金)
initState.deposit = () => ({
	// 首充 firstCharge。再充 reload
	status: '',
	// 新旧类型: 新首充:5,旧首充:2
	category: '',
	// [货币]最高奖金比例(百分比的值)
	maxRatio: '',
	// 5x6.code
	router: '',
	// [货币]奖金上限
	value: 0
})
// 待解锁奖金
initState.lockBonus = () => ({
	// 数组格式的原始数据
	list: [],
	// expiredAt
	endTimestamp: 0,
	// 未解锁的总奖金
	value: 0,
	// 下面是接口字段
	category: 0,
	bonusId: '',
	// 1.没有可解锁的奖金,
	// 有效期内: 2.有奖金未/可解锁 3.已解锁/可领取, 4.领完/时间结束
	totalAmount: 0,
	expiredAt: 0,
	clearTime: 0,
	// 是否过期
	isExpiredAt: true,
	// 全部已解锁的，包括了已解锁、已领取、在途
	unlockedAmount: 0,
	// 是已解锁但是未领取的;  0:去解锁, *>0 显示可领取
	notReceivedAmount: 0,
	// 是全部已领取的，包括已到账和在途的
	receivedAmount: 0
})
// 再充
initState.reloadDeposit = () => ({
	endTimestamp: 0,
	// [货币]最高奖金比例(百分比的值)
	maxRatio: '0',
	// [货币]奖金上限
	value: 0
})

const calcAmount = (keys: any, data: any) => {
	const total = keys.reduce((sum: any, key: any) => Decimals.add(sum, data[key] || 0), 0)
	return {
		value: total,
		_disabled: !(total > 0)
	}
}
const calcExpire = (item: any) => Decimals.sub(item.totalAmount, item.receivedAmount)

const handleShowNotification = async (string: string, isFinish = false) => {
	const activityStore = useActivityStore()
	activityStore.setShowNotification(false)
	await activityStore.deleteNotifications(string)
	if (Object.values(activityStore.notifications).filter((item) => item !== null).length > 0) {
		setTimeout(() => {
			!isFinish && activityStore.setShowNotification(true)
		}, 500)
	}
}

export const useActivityStore = defineStore('activity', {
	state: () => ({
		...initState(),
		config: {},
		userUpgradeInfo: {
			vip: {},
			star: {}
		},
		vipList: [] as Array<Member>,
		starList: [] as Array<Member>,
		vipLevelPanel: [],
		starLevelPanel: [],
		showRewardPopup: false,
		showRewardDetailPopup: false,
		showNotification: false,
		rewardPopupData: {} as any,
		rewardType: '',
		curentRewardTab: '',
		detailCardType: '',
		tab: 'vip',
		recordParams: {}
	}),
	actions: {
		changeTab(val: any) {
			this.tab = val
		},
		setUserUpgradeInfo(userUpgradeInfo: any) {
			this.userUpgradeInfo = userUpgradeInfo
		},
		async getUserUpgradeInfo() {
			try {
				// const { data } = await resUserUpgradeInfo()
				// this.setUserUpgradeInfo(data)
			} catch (error) {}
		},
		async getVipList() {
			try {
				const { data } = await getVipList()
				this.vipList = data
				const memberStore = useMemberStore()
				memberStore.vipList = data
			} catch (error) {}
		},
		async getStarList() {
			try {
				const { data } = await getStarList()
				this.starList = data
				const memberStore = useMemberStore()
				memberStore.starList = data
			} catch (error) {}
		},
		setRewardPopupShow(val: boolean) {
			this.showRewardPopup = val
		},
		setShowNotification(val: boolean) {
			this.showNotification = val
		},
		setRewardDetailPopupShow(val: boolean) {
			this.showRewardDetailPopup = val
		},
		setRewardPopupData(val: object) {
			this.rewardPopupData = val
		},
		setRecordParams(val: object) {
			this.recordParams = val
		},
		setRewardType(val: string) {
			this.rewardType = val
		},
		setDetailCardType(val: string) {
			this.detailCardType = val
		},
		setRewardsStatusItem({ key, value }: { key: keyof ReturnType<any>; value: object }) {
			Object.assign(this.status[key], value)
		},
		resetRewardsStatusItem(key: any) {
			Object.assign(this.status[key], initState().status[key])
		},
		setActivities(config: any) {
			this.activities = config
			// 按照 category 的值转换为对象格式
			if (config.length > 0) {
				config.forEach((item: any) => (this.activitiesObj[item.category] = item))
			} else {
				this.activitiesObj = {}
			}
		},
		setNotifications(value: object) {
			Object.assign(this.notifications, value)
		},
		deleteNotificationsItem(type: string) {
			this.notifications[type] = null
		},
		setUnlockBetRecord({ betType, field, list }: any) {
			this.unlockBetRecord[betType] = merge(this.unlockBetRecord[betType], keyBy(list, field))
		},
		setUpgradeRule({ type, value }: { type: 'vip' | 'star'; value: string }) {
			Object.assign(this.upgradeRule[type], value)
		},
		async getNotifications() {
			try {
				const accountStore = useAccountStore()
				const walletStore = useWalletStore()
				if (!accountStore.isLogin) return
				const res = await getNotifications()
				if (import.meta.env.DEV) {
					// const profileStore = useProfileStore()
					// res.data.upgradeVip = {
					// 	id: 'upgradeVip',
					// 	level: profileStore.vip
					// }
					//
					// res.data.upgradeStar = {
					// 	id: 'upgradeStar',
					// 	level: profileStore.star
					// }
					//
					// res.data.successFtd = {
					// 	id: 'successFtd',
					// 	bonus: 111,
					// 	currency: 'USDT',
					// 	endTimestamp: new Date().setHours(23, 59, 59, 999)
					// }
					// res.data.successReload = {
					// 	id: 'successReload',
					// 	bonus: 222,
					// 	currency: 'USDT',
					// 	endTimestamp: new Date().setHours(23, 59, 59, 999)
					// }
					// res.data.obtainChance = {
					// 	id: 'obtainChance',
					// 	bonus: 33,
					// 	bonusPercentage: '400',
					// 	currency: 'USDT',
					// 	endTimestamp: new Date().setHours(23, 59, 59, 999)
					// }
				}

				// 兼容接口字段  conditionalBonus => obtainChance
				if ('conditionalBonus' in res.data) {
					res.data.obtainChance = res.data.conditionalBonus
					delete res.data.conditionalBonus
				}

				if (res.data.successFtd?.id) {
					res.data.successFtd = {
						...res.data.successFtd,
						type: 'successFtd',
						isShow: true,
						title: 'popup.successFtd.title',
						subTitle: 'popup.successFtd.subTitle',
						icon: 'activity/locked.png',
						iconWidth: '226px',
						btnText: 'popup.successFtd.button',
						note: 'popup.successFtd.note',
						detailLink: 'popup.successFtd.detailsLink',
						countdown: res.data.successFtd.endTimestamp - Date.now() || 0,
						onClick: async () => {
							await handleShowNotification('successFtd')
						},
						onClickLink: async () => {
							await goDetails('rewards-bonus-ftd-postdeposit', {}, { replace: true })
							await handleShowNotification('successFtd', true)
						}
					}
				}
				if (res.data.upgradeVip?.id) {
					res.data.upgradeVip = {
						...res.data.upgradeVip,
						type: 'upgradeVip',
						isShow: res.data.upgradeVip.level > 0,
						title: 'popup.upgradeVip.title',
						subTitle: 'popup.upgradeVip.subTitle',
						extraSubTitle: 'rewards.levelPanel.viewVipLevelsBenefits',
						icon:
							Number(res.data.upgradeVip.level) === 0
								? 'activity/vip-level.svg'
								: this.vipList.find(({ level }) => res.data.upgradeVip.level === level)?.logo,
						typeIcon: res.data.upgradeVip.level > 0 ? 'server' : '',
						iconWidth: '226px',
						btnText: 'popup.upgradeVip.button',
						note: '',
						detailLink: '',
						onClickViewUrl: async () => {
							await router.push('/rewards-vip')
							this.curentRewardTab = 'benefits'
							this.setShowNotification(false)
							await handleShowNotification('upgradeVip', true)
						},
						countdown: res.data.upgradeVip.endTimestamp - Date.now() || 0,
						onClick: async () => {
							await handleShowNotification('upgradeVip')
						}
					}
				}
				if (res.data.upgradeStar?.id) {
					res.data.upgradeStar = {
						...res.data.upgradeStar,
						type: 'upgradeStar',
						isShow: res.data.upgradeVip.level > 1,
						title: 'popup.upgradeStar.title',
						subTitle: 'popup.upgradeStar.subTitle',
						extraSubTitle: 'rewards.levelPanel.viewStarLevelsBenefits',
						icon:
							Number(res.data.upgradeStar.level) === 0
								? 'activity/star-level.svg'
								: this.vipList.find(({ level }) => res.data.upgradeStar.level === level)?.logo,
						typeIcon: res.data.upgradeStar.level > 0 ? 'server' : '',
						iconWidth: '226px',
						btnText: 'popup.upgradeStar.button',
						note: '',
						detailLink: '',
						// viewUrl: '/rewards',
						onClickViewUrl: async () => {
							await router.push('/rewards-star')
							this.curentRewardTab = 'requirements'
							await handleShowNotification('upgradeStar', true)
						},
						countdown: res.data.upgradeStar.endTimestamp - Date.now() || 0,
						onClick: async () => {
							await handleShowNotification('upgradeStar')
						}
					}
				}
				if (res.data.obtainChance?.id) {
					res.data.obtainChance = {
						...res.data.obtainChance,
						type: 'obtainChance',
						isShow: true,
						title: 'popup.obtainChance.title',
						subTitle: [
							'popup.obtainChance.subTitle',
							{ percentage: percentage(res.data.obtainChance.bonusPercentage) }
						],
						icon: 'activity/vip-benefits/reload-bonus.png',
						btnText: 'popup.obtainChance.button',
						note: '',
						detailLink: 'popup.obtainChance.detailsLink',
						countdown: res.data.obtainChance.endTimestamp - Date.now() || 0,
						onClick: async () => {
							walletStore.setWalletDepositShow(true)
							await handleShowNotification('obtainChance', true)
						},
						onClickLink: async () => {
							await goDetails('rewards-bonus-reload-before-deposit', {}, { replace: true })
							await handleShowNotification('obtainChance', true)
						}
					}
				}
				if (res.data.successReload?.id) {
					res.data.successReload = {
						...res.data.successReload,
						type: 'successReload',
						isShow: true,
						title: 'popup.successReload.title',
						subTitle: 'popup.successReload.subTitle',
						icon: 'activity/locked.png',
						iconWidth: '226px',
						btnText: 'popup.successReload.button',
						note: 'popup.successReload.note',
						detailLink: 'popup.successReload.detailsLink',
						countdown: res.data.successReload.endTimestamp - Date.now() || 0,
						onClick: async () => {
							await handleShowNotification('successReload')
						},
						onClickLink: async () => {
							await goDetails('rewards-bonus-reload-after-deposit', {}, { replace: true })
							await handleShowNotification('successReload', true)
						}
					}
				}

				this.setNotifications(res.data)
			} catch (e) {
				console.error(e)
			}
		},
		async getRewardsConfig() {
			try {
				const appStore = useAppStore()
				const { data } = await getRewardsConfig({
					locationId: appStore.region
				})
				// store.commit('rewards/setRewardsConfig', res.data)
				const configData = data

				;[...configData.vip].reduce((pre, cur) => {
					const abs = Decimals.add(cur.growthValue, pre)
					cur._absoluteGrowth = abs
					return abs
				}, 0)
				// 计算STAR的累加绝对经验值; FIX STAR后台填写已经是绝对经验值
				// ;[...config.star].reduce((pre, cur) => {
				//   const abs = Decimals.add(cur.growthValue, pre)
				//   cur._absoluteGrowth = abs
				//   return abs
				// }, 0)
				this.config = configData
			} catch (e) {
				console.error(e)
				// showError(e)
			}
		},
		async getUpgradeRule(type: any) {
			try {
				const appStore = useAppStore()
				const res = await getUpgradeRule({
					locationId: appStore.region,
					type: type
				})
				this.setUpgradeRule({
					type: type,
					value: res.data
				})
			} catch (e) {
				console.error(e)
			}
		},
		async getProgressiveData() {
			try {
				const res = await getProgressive()

				// 首页展示: 没过期 && (优先展示 已完成但未领取的 || 正在进行的)
				const item =
					(Array.isArray(res.data)
						? res.data.filter((i: any) => !!i.expiredAt && i.notReceivedAmount)[0] ||
							find(res.data, (i) => !!i.expiredAt)
						: res.data) || {}

				if (import.meta.env.DEV) {
					// item.totalAmount = 10.1
					// item.unlockedAmount = 10
					// item.isExpiredAt = false
					// item.receivedAmount = 110
					// item.notReceivedAmount = 333
					// item.expiredAt = Date.now() + 60 * 60 * 24 * 1000 * 12
					// console.log('item=', item)
					// item.expiredAt = 1714911808519
				}
				this.resetRewardsStatusItem('lockBonus')
				this.resetRewardsStatusItem('expireBonus')
				// 待解锁奖金
				this.setRewardsStatusItem({
					key: 'lockBonus',
					value: {
						...item,
						endTimestamp: item?.expiredAt,
						value: Decimals.sub(item.totalAmount, item.unlockedAmount),
						list: Array.isArray(res.data) ? res.data : [res.data]
					}
				})
				// 过期奖金
				const expiredAmount = Array.isArray(res.data)
					? res.data.reduce(
							(p: number, c: any) => (c.isExpiredAt ? Decimals.add(p, calcExpire(c)) : p),
							0
						)
					: calcExpire(item)
				this.setRewardsStatusItem({
					key: 'expireBonus',
					value: { value: expiredAmount }
				})
			} catch (e) {
				console.error(e)
			}
		},
		vipPanel() {
			const profileStore = useProfileStore()
			const accountStore = useAccountStore()

			const base = {
				// VIP展示有0级,未登录和 已登录但0级 都展示默认
				current: { level: 0, name: 'VIP 0' },
				next: { level: 1, name: 'VIP 1' },
				progress: 0,
				isMaxLevel: false
			} as any
			const userInfo = profileStore.userInfo
			const vipList = this.vipList
			const upgradeInfo: any = this.userUpgradeInfo.vip
			// const level = userInfo?.vip
			const level = accountStore.isLogin ? Number(userInfo?.vip) : 0

			if (accountStore.isLogin) {
				const current = vipList.find((i: any) => i.level === level)
				const next = vipList.find((i: any) => i.level === Number(level) + 1)
				base.isMaxLevel = vipList.length && Number(level) >= Math.min(vipList.length, 30)
				// const { canUseDeposit, needVipGrowValue, oweExp } = upgradeInfo
				const canUseDeposit = upgradeInfo.canUseDeposit
				const needVipGrowValue = upgradeInfo.needVipGrowValue
				const oweExp = upgradeInfo.oweExp
				const percentage = Decimals.div(canUseDeposit, Decimals.add(needVipGrowValue, oweExp)) || 0

				base.progress = base.isMaxLevel ? 100 : (percentage * 100).toFixed(2)
				Object.assign(base.current, current)
				Object.assign(base.next, next)
			} else {
				Object.assign(base.next, vipList[0])
			}
			return base
		},
		starPanel() {
			const accountStore = useAccountStore()
			const profileStore = useProfileStore()
			const base = {
				current: { level: 1, name: 'STAR 1' },
				next: { level: 2, name: 'STAR 2' },
				progress: 0,
				isMaxLevel: false
			} as any
			const userInfo = profileStore.userInfo
			const starList = this.starList
			const upgradeInfo: any = this.userUpgradeInfo.star
			const level = accountStore.isLogin ? Number(userInfo?.star) : 0
			if (accountStore.isLogin) {
				const current = starList.find((i: any) => i.level === level)
				const next = starList.find((i: any) => i.level === level + 1)
				base.isMaxLevel = starList.length && level >= Math.min(starList.length, 30)
				// const { remainingStarExp, needStarGrowValue } = upgradeInfo
				const remainingStarExp = upgradeInfo.remainingStarExp
				const needStarGrowValue = upgradeInfo.needStarGrowValue
				const percentage = Decimals.div(remainingStarExp, needStarGrowValue) || 0
				base.progress = base.isMaxLevel ? 100 : (percentage * 100).toFixed(2)
				Object.assign(base.current, current)
				Object.assign(base.next, next)
			} else {
				Object.assign(base.current, starList[0])
				Object.assign(base.next, starList[1])
			}
			return base
			// this.starLevelPanel = base
		},
		async getBonusActivities() {
			const appStore = useAppStore()
			try {
				// TODO 考虑使用 useRequest 做防抖和依赖刷新
				const res = await getBonusActivities({
					locationId: appStore.region
				})

				this.setActivities(res.data)

				// 找出可获得最高奖金的项
				const maxBonusItem = res.data.reduce((maxItem: any, currentItem: any) => {
					if (currentItem.maxBonus > (maxItem ? maxItem.maxBonus : 0)) {
						return currentItem
					} else {
						return maxItem
					}
				}, null)
				// 首存奖金保存到 status.deposit 字段
				if (maxBonusItem) {
					this.setRewardsStatusItem({
						key: 'deposit',
						value: {
							...maxBonusItem,
							status: [2, 5].includes(maxBonusItem.category) ? 'firstCharge' : 'reload',
							endTimestamp: maxBonusItem.expiredAt,
							category: maxBonusItem.category,
							value: maxBonusItem.maxBonus,
							maxRatio:
								// 旧首充百分比是实际值,新首充是百分比的值
								maxBonusItem.category === 2
									? maxBonusItem.maxBonusPercentage * 100
									: maxBonusItem.maxBonusPercentage,
							// 区分新旧首充地址; TODO 临时写死: 后台配置不全,无法区分首充与解锁奖金与再充的TnC
							router:
								maxBonusItem.category === 5
									? 'rewards-bonus-ftd-predeposit'
									: maxBonusItem.category === 2
										? 'rewards-bonus-ftd'
										: maxBonusItem.router
						}
					})
				} else {
					this.resetRewardsStatusItem('deposit')
				}
			} catch (e) {
				console.error(e)
			}
		},
		async getRewardsStat() {
			try {
				const type = Object.keys(ActivityRewardType)
				const [res1, res0] = await Promise.all([
					getBonusStat({ status: RewardStatusEnum.SUCCESS.id, type }),
					getBonusStat({ status: RewardStatusEnum.INIT.id, type })
				])

				if (import.meta.env.DEV) {
					// res0.data.sportsRebate = 10
				}

				// 查询已领取的奖金
				this.setRewardsStatusItem({
					key: 'receivedBonus',
					value: calcAmount(ActivityBonusKeys, res1.data)
				})
				// 查询未领取返利和救援金
				this.setRewardsStatusItem({
					key: 'cashback',
					value: calcAmount(ActivityCashbackKeys, res0.data)
				})
				this.setRewardsStatusItem({
					key: 'sportsRebate',
					value: calcAmount(SportsRebateKeys, res0.data)
				})
				this.setRewardsStatusItem({
					key: 'slotsRebate',
					value: calcAmount(SlotsRebateKeys, res0.data)
				})
				this.setRewardsStatusItem({
					key: 'casinoRebate',
					value: calcAmount(CasinoRebateKeys, res0.data)
				})
			} catch (e) {
				console.error(e)
			}
		},
		depositButton() {
			// TODO 再充倒计时
			const walletStore = useWalletStore()
			const _state = reactive({
				text: 'rewards.deposit',
				disabled: false,
				loading: false,
				onClick: async () => {
					_state.loading = true
					walletStore.validateNavigation()
					// walletStore.setWalletDepositShow(true)
					// await router.push('/wallet')
					_state.loading = false
				}
			})
			return _state
		},
		rebateButton(data: any, status: any) {
			const state = reactive({
				text: 'rewards.claim',
				loading: false,
				disabled: !(status.value > 0),
				onClick: async () => {
					state.loading = true
					console.log('data.id ', data.id)
					await this.receiveBonus(data.id)
					// await store.dispatch('rewards/receiveBonus', data.id)
					state.loading = false
				}
			})
			return state
		},
		async deleteNotifications(type: string) {
			try {
				const item = this.notifications[type]
				// store.commit('rewards/deleteNotificationsItem', type)
				this.deleteNotificationsItem(type)
				await deleteNotifications({ id: item?.id })
			} catch (e) {
				console.error(e)
			}
		},
		receivedBonusButton() {
			const accountStore = useAccountStore()
			const activityStore = useActivityStore()
			const _state = reactive({
				text: 'rewards.bonus.details',
				disabled: !accountStore.isLogin,
				loading: false,
				onClick: async () => {
					_state.loading = true
					const item = {
						...RewardsHome.bonus,
						name: t(RewardsHome.bonus.name),
						subtitle: t('rewards.bonusSubtitle'),
						type: 'bonus',
						bgColor: 'bg-gradient-5',
						bgColorPopup: 'rewards-bonus',
						icon: 'activity/bonus.png',
						button: activityStore.receivedBonusButton(),
						amount: activityStore.status.receivedBonus
					}
					// activityStore.setBonusType(item.type)
					activityStore.setRewardPopupData(item)
					activityStore.setRewardPopupShow(true)
					_state.loading = false
				}
			})
			return _state
		},
		lockBonusButton() {
			// 有已解锁的奖金 ? 显示领取 点击领取奖金 : 则显示解锁 点击去解锁
			const hasUnlocked = this.status.lockBonus.notReceivedAmount > 0
			const _state = reactive({
				text: hasUnlocked ? 'rewards.claimable' : 'rewards.unlock',
				disabled: false,
				loading: false,
				onFinish: () => this.getProgressiveData(),

				onClick: async () => {
					_state.loading = true
					hasUnlocked ? await this.receiveBonus(this.status.lockBonus.type) : await router.push('/')
					_state.loading = false
				}
			})
			return _state
		},
		weeklyBonusButton() {
			return {}
		},
		async receiveBonus(type: any) {
			try {
				await receiveBonus({ type: RewardsEnumDiff[type] || type })
				// showToast(t('contestTask.receiveSuccess'))
				console.log(t('contestTask.receiveSuccess'))
				await Promise.all([this.getRewardsStat(), this.getProgressiveData()])
			} catch (error) {
				console.error(error)
			}
		},
		async getUnlockBetRecord(list: any) {
			try {
				const appStore = useAppStore()
				const betTypeMap: any = {}
				list.forEach((item: any) => {
					const betType = item?.origin?.message?.betType
					if (betType) {
						betTypeMap[betType] = betTypeMap[betType]
							? betTypeMap[betType].concat(item.orderNo)
							: [item.orderNo]
					}
				})
				const [slotRes, sportsRes] = await Promise.all([
					betTypeMap.slot &&
						getSlotsRecordDetailList({
							locale: appStore.lang,
							betOrderThreeStr: betTypeMap.slot.join(',')
						}),
					betTypeMap.realMoney &&
						getBetList({
							locale: appStore.lang,
							status: BettingStatus.settlemented,
							// status: BettingOrderStatus.settlement.id,
							orderBy: 'settled_at',
							page: 1,
							pageSize: 1000,
							orderNos: betTypeMap.realMoney.join(',')
						})
				])
				if (Array.isArray(slotRes?.data)) {
					// store.commit('rewards/setUnlockBetRecord', {
					// 	betType: BetType.slot.id,
					// 	field: 'betOrder',
					// 	list: slotRes?.data
					// })
					this.setUnlockBetRecord({
						betType: BetType.slot.id,
						field: 'betOrder',
						list: slotRes?.data
					})
				}
				if (Array.isArray(sportsRes?.data?.list)) {
					// store.commit('rewards/setUnlockBetRecord', {
					// 	betType: BetType.realMoney.id,
					// 	field: 'orderNo',
					// 	list: sportsRes?.data?.list
					// })
					this.setUnlockBetRecord({
						betType: BetType.realMoney.id,
						field: 'orderNo',
						list: sportsRes?.data?.list
					})
				}
			} catch (e) {
				console.error(e)
			}
		}
	},

	getters: {},
	persist: true
})
